package com.leanote.berial.tingphone.client;

/**
 * Created with InetlliJ IDEA.
 * Project: com.liuhui.zhufengfm.app.client
 * user  Pinocchio
 * Date 2015/7/28
 * Email:liu594545591@126.com
 */

import android.os.Build;
import com.leanote.berial.tingphone.util.StreamUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * 网络工具类,用于请求get post请求
 */
public final class HttpUtil {

    public static final int TIMEOUT_MILLIS = 5000;
    public static final int TIMEOUT_READ = 5000;

    private HttpUtil() {

    }
    ////////////////////////////

    /**
     * 获取GET请求,返回字节数组
     *
     * @param url
     * @return 返回字节数组
     */
    public static byte[] doGet(String url) {
        byte[] ret = null;
        if (url != null) {
            URL u = null;
            //注意释放连接
            HttpURLConnection conn = null;
            InputStream is = null;
            try {
                u = new URL(url);
                conn = (HttpURLConnection) u.openConnection();
                conn.setRequestMethod("GET");
//                conn.setDoInput(true);
                conn.setRequestProperty("Accept-Encoding", "gzip");//设置http请求头
                conn.setRequestProperty("User-Agent", "ting_4.1.7(MI2,Android" + Build.VERSION.SDK_INT);
                //设置联网超时,只能够用于短时间的联网操作
                //长时间的自己在写一套,例如下载1G

                //Socket打开链接的时间
                conn.setConnectTimeout(TIMEOUT_MILLIS);
                //链接一共可以读多长时间
                conn.setReadTimeout(TIMEOUT_READ);

                //连接的属性
                //设置自动处理 302和307跳转  通常返回200
                conn.setInstanceFollowRedirects(true);
                //连接
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    is = conn.getInputStream();
                    //获取服务器头信息,内容是否压缩
                    String contentEncoding = conn.getHeaderField("Content-Encoding");
                    if (contentEncoding == null) {
                        contentEncoding = conn.getHeaderField("content-encoding");
                    }
                    if (contentEncoding != null && contentEncoding.equals("gzip")) {
                    //代表数据经过压缩
                        //使用GZIPInputStream解压缩
                        is = new GZIPInputStream(is);
                    }
                    //读输入流
                        ret = StreamUtil.readStream(is);

                } else {
                    //TODO 其他情况 304  301
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                StreamUtil.close(is);
                StreamUtil.close(conn);
            }
        }
        return ret;
    }
}
